package provider

import (
	. "cppcloud"
	"fmt"
	"math/rand"
)

// 创建TCP服务提供者入口

type TCPProvider struct {
	*ProviderBase
	*TCPServiceManage
}

// CreateTCPProvider 创建入口1: 只提供监听端口来创建
// port: 当为0时，用随机端口
// host: 当为空时，用cloudapp socker ip
// 注意，如果所连接的Serv和本服务不同网段时（比如Serv在外网）需要调用SetUrl()显式给出服务地址
func CreateTCPProvider(cloudapp *CloudApp, host string, port int) (pvrd *TCPProvider) {
	pbase := CreateProviderBase(cloudapp)
	pbase.SetRegName(cloudapp.SvrName())
	pbase.SetScheme("tcp")
	pbase.SetHost(host)

	if 0 == port {
		port = 1024 + rand.Intn(1000)
	}
	pbase.SetPort(port)
	tcpmgr, err := createTCPServiceManage(host + ":" + fmt.Sprint(port))
	if nil != err {
		fmt.Println("CREATETCPSERVICE| msg=", err)
		return nil
	}

	tcpmgr.resultCallBack = pbase.TellResult
	if "" == host {
		host = cloudapp.CliIP()
		pbase.SetHost(host)
	}

	pvrd = &TCPProvider{
		pbase,
		tcpmgr,
	}
	cloudapp.AddNotifyCallBack("shutdown", pvrd.onAppShutdown)
	return
}

func (pvrd *TCPProvider) Start() {
	pvrd.waitGroup.Add(1)
	go pvrd.run()
	pvrd.Regist(true)
}

func (pvrd *TCPProvider) onAppShutdown(param map[string]interface{}) (code int, result interface{}) {
	pvrd.Shutdown()
	return 0, nil
}
